from cold_start_analyzer.base_analyzer import BaseAnalyzer
from cold_start_analyzer.consts import NOT_AVAILABLE
from cold_start_analyzer import db_helper
from cold_start_analyzer.log_helper import dlog


class Phase3All(BaseAnalyzer):
    description = "应用初始化: 从HandleLaunchApplication结束到JsWindowStage::OnLoadContent开始"
    """
    起点： app_thread
    H:void OHOS::AppExecFwk::MainThread::HandleLaunchApplication 结束
    终点： app_thread
    H:Native async work complete callback, name:JsWindowStage::OnLoadContent 开始
    """
    def get_result(self):
        if 'Phase2All' not in self.context:
            dlog.error(f"Phase2All not in context: {self.context}")
            return NOT_AVAILABLE
        start_ts = self.context['Phase2All']['end_ts']
        patterns = [
            '%Native async work complete callback, name:JsWindowStage::OnLoadContent%',
            '%OnLoadContent%'
        ]
        event = db_helper.get_first_event_after(self.cursor, patterns, start_ts=start_ts, thread_name=self.thread_name)
        if not event:
            dlog.warning(f"OnLoadContent marker not found for thread {self.thread_name}")
            return NOT_AVAILABLE
        end_ts = event[0]
        if end_ts <= start_ts:
            dlog.warning(f"OnLoadContent marker ts {end_ts} <= start {start_ts} for thread {self.thread_name}")
            return NOT_AVAILABLE
        self.context['Phase3All'] = {
            'start_ts': start_ts,
            'end_ts': end_ts,
            'marker': event[3],
        }
        return end_ts - start_ts
